class Lazyload {
  constructor() {
    // 初始化首页的页面图片
    window.addEventListener('scroll', this.throttle(this.lazyload.bind(this), 500, 500), false)
  }

  throttle(fn, delay, atleast) {
    let timeout = null,
      startTime = new Date()
    return function() {
      const curTime = new Date()
      clearTimeout(timeout)
      if (curTime - startTime >= atleast) {
        fn()
        startTime = curTime
      } else {
        timeout = setTimeout(fn, delay)
      }
    }
  }
  // getBoundingClientRect 是图片懒加载的核心
  lazyload() {
    const arr = document.querySelectorAll('.loading')
    const that = this
    let n = 0
    for (let i = n, len = arr.length; i < len; i++) {
      if (arr[i].getBoundingClientRect().top < document.documentElement.clientHeight && !arr[i].isLoad) {
        arr[i].isLoad = true //图片显示标志位
        arr[i].style.cssText = 'transition: filter 0.3s linear;filter: blur(10px);'
        ;(function(i) {
          setTimeout(function() {
            if (arr[i].dataset) {
              //兼容不支持data的浏览器
              that.aftLoadImg(arr[i], arr[i].dataset.original)
            } else {
              that.aftLoadImg(arr[i], arr[i].getAttribute('data-original'))
            }
            arr[i].style.cssText = 'transition: filter 0.3s linear;filter: blur(0);' //相当于fadein
          }, 500)
        })(i)
      }
      n = n + 1
    }
  }

  aftLoadImg(obj, url) {
    let oImg = new Image()
    oImg.onload = function() {
      obj.src = oImg.src //下载完成后将该图片赋给目标obj目标对象
    }
    oImg.src = url //oImg对象先下载该图像
  }
}

export default Lazyload
